package main

import (
	"fmt"
	"sort"
)

func main() {
	nums := []int{2, 3, 4, 2, 1, 42, 3}
	frequent := topKFrequent(nums, 2)
	fmt.Println(frequent)
}
func topKFrequent(nums []int, k int) []int {
	m := make(map[int]int) //map用于存储每个元素出现的次数
	s := make([]int, 0)    //用于记录不同的元素

	for _, v := range nums {
		val, istrue := m[v]
		if istrue { //如果键对应的值存在
			m[v] = val + 1 //则值加1
		} else {
			m[v] = 1 //如果值不存在
			s = append(s, v)
		}
	}

	sort.Slice(s, func(i, j int) bool { //然后根据出现次数的大小对s进行排序
		return m[s[i]] > m[s[j]]
	})

	return s[:k]

}
